package com.superlc.ssm.core.shiro.filter;

import com.superlc.ssm.core.shiro.util.ShiroKit;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.web.servlet.OncePerRequestFilter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import java.io.IOException;

/**
 * @ProjectName: ssm$
 * @Package: com.superlc.ssm.core.filter$
 * @ClassName: AddPrincipleToSessionFilter$
 * @Description:
 * OncePerRequestFilter 没有
 * 使用rememberMe 功能时，会问session中的用户属性，将玩家属性加入session 过滤器
 * @Author: super
 * @CreateDate: 2018/8/24$ 17:08$
 * @UpdateUser: 更新者
 * @UpdateDate: 2018/8/24$ 17:08$
 * @UpdateRemark: 更新内容
 * @Version: 1.0
 */
public class AddPrincipalToSessionFilter extends OncePerRequestFilter {

        private final Logger logger = LoggerFactory.getLogger(this.getClass());

        @Override
        protected void doFilterInternal(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws ServletException, IOException {
            Subject subject = SecurityUtils.getSubject();
            if (ShiroKit.isAuthenticated() ||ShiroKit.getUser()!=null ||subject.isRemembered()) {
                Object principle = subject.getPrincipal() ;
                Session session = subject.getSession(false);
                if(session.getAttribute("userInfo")==null){
                    session.setAttribute("userInfo",principle);
                    logger.info("Add principal info to session: " + principle.toString());
                }
            }
            filterChain.doFilter(servletRequest, servletResponse);
        }
}
